package config

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/sirupsen/logrus"
)

// Config 应用配置结构
type Config struct {
	StaticFolder         string `json:"static_folder"`
	NotFoundPage         string `json:"not_found_page"`
	Host                 string `json:"host"`
	Port                 string `json:"port"`
	DevInterceptorEnabled bool   `json:"dev_interceptor_enabled"`
	DevUsername          string `json:"dev_username"`
	DevPassword          string `json:"dev_password"`
}

// DefaultConfig 返回默认配置
func DefaultConfig() Config {
	return Config{
		StaticFolder:          "static",
		NotFoundPage:          "404.html",
		Host:                  "127.0.0.1",
		Port:                  "8080",
		DevInterceptorEnabled: false,
		DevUsername:           "admin",
		DevPassword:           "password",
	}
}

// ReadConfig 从文件读取配置，如果文件不存在则创建默认配置
func ReadConfig(logger *logrus.Logger) (Config, error) {
	config := DefaultConfig()

	configData, err := os.ReadFile("config.json")
	if err != nil {
		logger.Printf("Failed to read config file: %v", err)

		// 创建默认配置文件
		configData, err = json.MarshalIndent(config, "", "  ")
		if err != nil {
			return config, fmt.Errorf("failed to marshal default config: %w", err)
		}

		if err := os.WriteFile("config.json", configData, 0644); err != nil {
			return config, fmt.Errorf("failed to write default config file: %w", err)
		}

		logger.Printf("Created default config file: config.json")
	} else {
		if err := json.Unmarshal(configData, &config); err != nil {
			return config, fmt.Errorf("failed to unmarshal config: %w", err)
		}
	}

	return config, nil
}

// WriteConfig 将配置写入文件
func WriteConfig(config Config) error {
	configData, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal config: %w", err)
	}

	return os.WriteFile("config.json", configData, 0644)
}